#!/usr/bin/env bash
set -e
##
#  mac (en0),Linux(eth0) 自动获取内网 ip
#  分别在 node1,node2,node3 机器分别执行: 
#        ./etcd.sh up <node1> <node2> <node3>
#  启动: ./etcd.sh up 192.168.1.107 192.168.1.108 192.168.1.109
##

# 文档: https://github.com/etcd-io/etcd/blob/master/Documentation/demo.md
# 文档: https://github.com/etcd-io/etcd

# 存储路径
dataDir=/data/etcd-data

if [ ! -d "$dataDir" ];then
    mkdir -p $dataDir
fi

if [ $# -eq 0 ];
then
    echo "Usage: $0 <ip1> <ip2>"
    exit
fi

# AllNodeDict=(['etcd1']=10.0.0.1 ['etcd2']=10.0.0.2)
declare -A AllNodeDict
createDictData(){
    for i in `seq 1 $#`;do
        AllNodeDict["etcd"$i]=$1
        shift
    done
}
# 获取本机 IP
getIp(){
    # mac
    if [[ `uname` == 'Darwin' ]];then
        echo `ifconfig en0 | awk -F '[" ":]+' 'NR==4{print $2}'`
    else
    #  linux
        echo `ip address show  eth0  | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*'`
    fi
}
# 获取指定 ip 所在的 dict key
getIPKey(){
    for node in ${!AllNodeDict[@]};do
        if [[ ${AllNodeDict[$node]} == $1 ]];then
            echo $node
            break
        fi
    done
}
# 查看集群健康
checkClusterHealth(){
    etcd_servers=$( for i in ${!AllNodeDict[@]};do  echo http://${AllNodeDict[$i]}:2379; done | sort | paste -d, -s - )
    docker exec -it etcd /bin/sh -c "export ETCDCTL_API=2  && etcdctl --endpoints $etcd_servers cluster-health"
}
# 创建集群
create_cluster(){
    echo Creating cluster master
    ip=`getIp`
    echo "----------- 本机IP: $ip -----------"
    node=`getIPKey $ip`
    clusterList=`for i in ${!AllNodeDict[@]};do  echo $i=http://${AllNodeDict[$i]}:2380; done | sort | paste -d, -s - `
    echo docker run -d --restart=always --name etcd \
        -p 2379:2379 \
        -p 2380:2380 \
        --volume=$dataDir:/etcd-data \
        registry.aliyuncs.com/google_containers/etcd:3.3.10 \
        etcd --data-dir=/etcd-data --name $node \
        --initial-advertise-peer-urls http://$ip:2380 --listen-peer-urls http://0.0.0.0:2380 \
        --advertise-client-urls http://$ip:2379 \
        --listen-client-urls http://0.0.0.0:2379 \
        --initial-cluster-state new \
        --initial-cluster-token docker-etcd \
        --initial-cluster $clusterList
}



case $1 in
    up)
        shift
        createDictData $@
        create_cluster
        ;;
    check)
        shift
        createDictData $@
        checkClusterHealth
        ;;
    *)
        echo "Unknow command..."
        exit 1
        ;;
esac
